from time import sleep
import log
import bitbrowser_api as api
import asyncio
from pyppeteer import *

async def op_follow(ws_link):
    log.Info(f"Browser list:{ws_link}")

    try:

        browser = await connect({'browserWSEndpoint': ws_link})
        page = await browser.newPage()
        await page.setViewport({'width': 1366, 'height': 1024})
        
        log.Info(f"开始处理{ws_link}")
        log.Info(f"打开页面")
        # 打开Facebook Marketplace销售页面
        await page.goto('https://facebook.com/friends', {
            'waitUntil': 'networkidle2',
            'timeout': 60000
        })
        
        # 等待页面加载完成
        await page.waitForSelector('body')

        log.Info("开始执行关注操作")

        # 获取所有具有特定class的元素
        # 注意：这里使用CSS选择器，将class中的空格替换为点，并在前面加上点
        class_selector = '.x1ja2u2z.x78zum5.x2lah0s.x1n2onr6.xl56j7k.x6s0dn4.xozqiw3.x1q0g3np.x14ldlfn.x1b1wa69.xws8118.x5fzff1.x972fbf.x10w94by.x1qhh985.x14e42zd.x9f619.xpdmqnj.x1g0dm76.xtvsq51.x1r1pt67'
        elements = await page.querySelectorAll(class_selector)
        
        # 确定要点击的元素数量
        num_to_click = min(len(elements), 6)
        
        # 点击元素
        for i in range(num_to_click):
            try:
                await elements[i].click()
                log.Info(f"已点击第{i+1}个元素")
                await asyncio.sleep(2)  # 间隔2秒
            except Exception as e:
                log.Error(f"点击第{i+1}个元素失败:{e}")
        
        log.Info(f"已完成点击{num_to_click}个元素")
        
    except Exception as e:
        log.Error(f"处理{ws_link}失败:{e}")
        return False


if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(op_follow(api.get_pyppeteer_wslink_by_ids(api.get_alive_ids()[0])))
